// pages/home/detail/index.js
import {
  getDynamycByIdApi,
  getDynamycCommentApi,
  postDynamicApi,
  postDynamycCommentApi,
  postDynamycCollect,
  getDynamycCommentReplyApi,
  postDynamycLike
} from '../../../https/dynamic'
import {
  BASE_URL
} from '../../../constant/index'
import {
  getIsFollowingApi,
  postFollowApi,
  postUnFollowApi
} from '../../../https/user'
import {
  addHistory,
  removeHistory
} from '../../../utlis/localHistory'
Page({

  /**
   * 页面的初始数据
   */
  data: {
    BASE_URL,
    detail: {},
    isFollowing: false, // 是否关注
    keyboardHeight: 0, // 键盘高度
    replyTxt: "", // 回复框内容
    showInput: false,
    focus: false,
    maskAnimation: {},
    commentList: [], // 评论列表
    commentId: "", // 二级评论id
    page: 1,
    limit: 20,
    total: 100,
    showMore: false
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    const docid = options.docid
    this.getDynamycDetail(docid)
    this.getDynamycComment(docid)

  },
  // 获取是否关注用户
  async getIsFollowing(userId) {
    const getRes = await getIsFollowingApi({
      id: userId
    })
    if (getRes.code == 200) {
      this.setData({
        isFollowing: getRes.data
      })
    }
  },
  // 切换关注状态
  async toggleFollow() {
    const id = this.data.detail.user.id
    const isFollowing = this.data.isFollowing
    if (isFollowing) {
      const postRes = await postUnFollowApi({
        id
      })
    } else {
      const postRes = await postFollowApi({
        id
      })
      if (postRes.code == 200) {
        wx.showToast({
          title: '关注成功',
          icon: 'success'
        })
      }
      if (postRes.statusCode == 403) {
        wx.showToast({
          title: '请先登录后才可评论',
          icon: "none"
        })
        return
      }
    }
    this.getIsFollowing(id)

  },
  // 获取动态详情
  async getDynamycDetail(docid) {
    const getRes = await getDynamycByIdApi({
      id: docid
    })
    if (getRes.code == 200) {
      this.setData({
        detail: getRes.data
      })
      // 本地存储
      addHistory(getRes.data)
      this.getIsFollowing(getRes.data.user.id)
    } else {
      wx.showToast({
        title: '动态已被删除',
        icon: 'error'
      })
      removeHistory(docid)
      setTimeout(() => {
        wx.navigateBack()
      }, 1000)
    }
  },
  // 获取一级评论
  async getDynamycComment(docid) {
    const {
      page,
      limit,
      total
    } = this.data

    const getRes = await getDynamycCommentApi({
      page,
      limit,
      dynamycId: docid
    })
    if (getRes.code == 200) {
      this.setData({
        commentList: getRes.data.list,
        total: getRes.data.total
      })
    }
  },
  // 获取二级评论
  async getSecondReply(e) {
    wx.showLoading({
      title: '加载中..',
    })
    const commentId = e.currentTarget.dataset.commentid
    const getRes = await getDynamycCommentReplyApi({
      commentId
    })
    if (getRes.code == 200) {
      const commentList = this.data.commentList
      commentList.map(item => {
        if (item.id == commentId) {
          item.children = getRes.data
        }
        return item
      })
      this.setData({
        commentList
      })
    }
    wx.hideLoading()
  },
  // 收起二级评论
  async deleteComment(e) {
    wx.showLoading({
      title: '加载中..',
    })
    const commentId = e.currentTarget.dataset.commentid

    const commentList = this.data.commentList
    commentList.map(item => {
      if (item.id == commentId) {
        delete item.children
      }
      return item
    })
    this.setData({
      commentList
    })

    wx.hideLoading()
  },
  // 添加评论
  async addComment() {
    const {
      replyTxt,
      detail,
      commentId

    } = this.data
    if (!replyTxt) {
      wx.showToast({
        title: '请输入评论内容',
        icon: 'none'
      })
      return
    }
    wx.showLoading({
      title: '评论中..',
    })

    const addRes = await postDynamycCommentApi({
      dynamicId: detail.id,
      comment: replyTxt,
      commentId
    })
    console.log(addRes)
    this.closePopup()
    if (addRes.code == 201) {
      wx.showToast({
        title: '发送成功',
        icon: 'none'
      })
      if (commentId) {
        const commentList = this.data.commentList.map(item => {
          if (item.id == commentId) {
            item.childrenCount++
          }
          return item
        })
        this.setData({
          commentList: commentList
        })
        this.getSecondReply({
          currentTarget: {
            dataset: {
              commentid: commentId
            }
          }
        })
      } else {
        this.getDynamycComment(detail.id)
      }
    } else if (addRes.statusCode == 403) {
      wx.showToast({
        title: '请先登录后才可评论',
        icon: "none"
      })
    } else {
      wx.showToast({
        title: addRes.message,
        icon: 'error'
      })
    }
    wx.hideLoading()

  },
  // 输入框事件
  bindInput(e) {
    const value = e.detail.value
    this.setData({
      replyTxt: value
    })
  },
  // 关闭弹框
  closePopup() {
    console.log(11111)
    this.setData({
      showInput: false,
      showMore: false,
      replyTxt: ""
    })
  },
  // 回复评论
  bindshowReply(e) {
    const commentId = e.currentTarget.dataset.commentid

    this.setData({
      showInput: true,
      commentId

    })
    setTimeout(() => {
      this.setData({
        focus: true
      })
    }, 450);
  },
  // 点赞
  async bindLike() {
    const id = this.data.detail.id
    const res = await postDynamycLike({
      id
    })
    if (res.code == 200) {
      wx.showToast({
        title: res.message,
        icon: 'none'
      })
      this.setData({
        'detail.isLike': res.data
      })
    }
    if (res.statusCode) {
      wx.showToast({
        title: '请先登录后进行操作',
        icon: "none"
      })
    }

  },
  // 收藏
  async bindCollect() {
    const id = this.data.detail.id
    const res = await postDynamycCollect({
      id
    })
    if (res.code == 200) {
      wx.showToast({
        title: res.message,
        icon: 'none'
      })
      this.setData({
        'detail.isCollect': res.data
      })
    }
    if (res.statusCode) {
      wx.showToast({
        title: '请先登录后进行操作',
        icon: "none"
      })
    }
  },
  // 显示图片
  bindPreviewImage(e) {
    console.log(e)
    const url = e.currentTarget.dataset.url
    const urllist = e.currentTarget.dataset.urllist
    console.log(url, urllist)
    const urls = urllist.map(item => BASE_URL + item)
    wx.previewImage({
      current: BASE_URL + url,
      urls: urls
    });
  },
  // 打开更多
  openMore() {
    this.setData({
      showMore: true
    })
  },
  // 跳转用户详情
  gotoMyDetail(e) {
    const docid = e.currentTarget.dataset.docid
    wx.navigateTo({
      url: '../../my/detail/index?docid=' + docid,
    })
  },
  // 跳转举报界面
  gotoReport(e) {
    const docid = this.data.detail.id

    const user = wx.getStorageSync('userData')
    console.log(user)
    if (!user) {
      wx.showToast({
        title: '请先登录',
        icon: 'none'
      })
      this.setData({
        showMore: false
      })
      return
    }

    wx.navigateTo({
      url: '../../my/report/index?docid=' + docid,
    })
    this.setData({
      showMore: false
    })
  },
  // 跳转私聊界面
  gotoChat(e) {
    // const docid = e.currentTarget.dataset.docid
    const userId = this.data.detail.user.id

    const user = wx.getStorageSync('userData')
    console.log(user)
    if (!user) {
      wx.showToast({
        title: '请先登录',
        icon: 'none'
      })
      this.setData({
        showMore: false
      })
      return
    }
    if (userId == user.id) {
      wx.showToast({
        title: '不能与自己私聊',
        icon: 'none'
      })
      this.setData({
        showMore: false
      })
      return
    }
    // return

    wx.navigateTo({
      url: '../../message/chat/index?docid=' + userId,
    })
    this.setData({
      showMore: false
    })
  },


})